// Copyright  2004-2008 Backplane Ltd.
//
// This file is part of DOM3XPath
//
// DOM3XPath is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
//
// DOM3XPath is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License
// along with DOM3ImplReg. If not, see <http://www.gnu.org/licenses/>.
//	
//
//   Purpose:  Implementation of CFileInfo
//   $Id$

#include "stdafx.h"
#include "FileInfo.h"

#include "ReturnCodes.h"
#include "comutil.h"
// CFileInfo

STDMETHODIMP CFileInfo::InterfaceSupportsErrorInfo(REFIID riid)
{
	static const IID* arr[] = 
	{
		&IID_IFileInfo
	};

	for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
	{
		if (::InlineIsEqualGUID(*arr[i],riid))
			return S_OK;
	}
	return S_FALSE;
}

STDMETHODIMP CFileInfo::mimeTypeFromExtension(BSTR sExtension, BSTR * psMimeType)
{
	HRESULT hr = S_OK;
	HKEY pNewKey;

	//if the user has supplied a filename, or an extension
	//	with a leading '.' find the start of the actual extension.
	wchar_t * wsExtension = wcsrchr(sExtension,L'.');
	if(wsExtension)
	{
		wsExtension++;
	}
	else
	{
		wsExtension = sExtension;
	}

	CComBSTR bsKey("SOFTWARE\\classes\\.");
	
	bsKey += wsExtension;
	char * pcKey = _com_util::ConvertBSTRToString(bsKey);
	long lErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE,pcKey,0,KEY_READ,&pNewKey);

	if(pNewKey)
	{
		DWORD len = 0;
		lErr = RegQueryValueEx(pNewKey,"Content Type",0,0,0,&len);
		if(len)
		{
			unsigned char * sValue = new unsigned char[len];
			DWORD dwType = 0;
			lErr = RegQueryValueEx(pNewKey,"Content Type",0,&dwType,sValue,&len);
			if(REG_SZ == dwType)
			{
				*psMimeType = CComBSTR(reinterpret_cast<char*>(sValue)).Detach();
			}
			delete[] sValue;
		}
		else
		{
			hr = RL_E_NOMIMETYPE;
			SetupErrorInfo(hr,wsExtension);
		}
		RegCloseKey(pNewKey);
	}
	else
	{
		hr = RL_E_BADEXT;
		SetupErrorInfo(hr,wsExtension);
	}
	delete pcKey;
	return hr;
}
